<?php

namespace App\Http\Controllers\Company\Auth;

use App\Jobs\CompanyRegisterEmail;
use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyTrialError;
use App\Models\Company\CompanyUser;
use App\Models\Company\CompanyVisitRecord;
use App\Models\Personal\PersonalTrialError;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth, Validator, CustomPassword;
use Session;


class AuthController extends Controller{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    //登录以后跳转到什么位置
    protected $redirectTo = '/company/welcome';
    //退出以后跳转到什么位置
    protected $redirectAfterLogout = '/';
    protected $guard = 'company';
    protected $loginView = 'default.company.auth.login';
    protected $registerView = 'default.company.auth.register';
    protected $username = 'username';

    /**
     * 除了退出其它多要自动验证
     * AuthController constructor.
     */
    public function __construct(){
        $this->middleware('guest:company', ['except' => 'logout']);
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request){
        $validator = $this->validator($request->all());
        if($validator->fails()){
            $this->throwValidationException(
                $request, $validator
            );
        }

        Auth::guard($this->getGuard())->login($this->create($request->all()));
        $user = auth()->guard('company')->user();
        //注册记录表
        $record = array();
        $record['uid'] = $user->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 1;
        //检查是不是企业注册
        if(!empty($request->openIdType) == 'mp'){
            $record['type'] = 3;
        }else{
            if(empty($request->openId)){
                $record['type'] = 1;
            }else{
                $record['type'] = 2;
            }
        }
        //登录记录表和突访记录表
        CompanyLoginRecord::create($record);
        CompanyVisitRecord::create($record);

        //判断是什么类型注册
        if(!empty($request->email)){
            $user = auth()->guard('company')->user();
            $userInfo = (object)null;
            $userInfo->uid = $user->uid;
            $userInfo->email = $user->email;
            $userInfo->username = $user->username;
            $userInfo->password = $request->password;
            //添加到队列中
            $this->dispatch(new CompanyRegisterEmail($userInfo));
        }
        //删除验证码的session数据
        $request->session()->forget('mobile_verification');
        $request->session()->forget('mobile_verification_code');
    }


    /**
     * 注册提交
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request){
        $this->register($request);
        return redirect("company/register_basic");
    }

    /**
     * 企业会员前台注册验证方法
     * @param array $data
     * @return mixed
     */
    protected function validator(array $data){
        $message = [
            'company_name.required' => '公司名称必须填写',
            'contacts.required' => '联系人必须填写',
            'mobile.mobile_verification' => '手机号码不正确',
            'mobCode.required' => '手机验证码不能为空',
            'mobCode.mobile_verification_code' => '手机号码和发送的验证码不匹配',
            'phone.check_phone' => '电话号码不正确',
            'username.required' => '用户名必须填写',
            'username.alpha_dash' => '用户名可以允许字母、数字、底线_',
            'username.unique' => '该用户名已存在',
            'username.max' => '用户名称最多20个字符',
            'username.mobile' => '用户名不能使用手机号码',
            'email.email' => '邮箱格式不正确',
            'password.required' => '密码必须填写',
            'password.between' => '密码必须在6-20位之间',
            'password.confirmed' => '确认密码和密码必须一致',
        ];
        return Validator::make($data, [
            'company_name' => 'required',
            'contacts' => 'required',
            'email' => 'email',
            'mobile' => 'mobile_verification',
            'mobCode' => 'required|mobile_verification_code:' . $data['mobile'],
            'phone' => 'check_phone:' . $data['area_code'] . ',' . $data['ext'],
            'username' => 'required|max:20|alpha_dash|unique:company_users,username|mobile',
            'password' => 'required|between:6,20|confirmed',
        ], $message);
    }

    /**
     * 企业会员前台注册验证字段
     * @param array $data
     * @return static
     */
    protected function create(array $data){
        $phone = $data['area_code'] . '-' . $data['phone'] . '-' . $data['ext'];
        $phone = trim($phone, '-');
        if(!empty($data['openId'])){
            if($data['openIdType'] == 'mp'){
                if(!Session::has('openId')){
                    return redirect('/company/login')->with('errMsg', '绑定失败，请重试一下！');
                }
                //微信
                if(CompanyUser::select('wechatopenid')->where('wechatopenid', $data['openId'])->first()){
                    return back()->withErrors(['username' => '绑定失败，该微信已绑定过其它账号！']);
                }
                return CompanyUser::create([
                    'username' => $data['username'],
                    'password' => CustomPassword::make($data['password']),
                    'mobile' => $data['mobile'],
                    'contacts' => $data['contacts'],
                    'company_name' => $data['company_name'],
                    'email' => $data['email'],
                    'regip' => getIp(),
                    'phone' => $phone,
                    'wechatopenid' => session('openId'),
                    'wechatunionid' => session('unionid')?session('unionid'):null,
                    'last_login_ip' => getIp(),
                    'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                    'regtime' => date('Y-m-d H:i:s', time()),
                    'surpris_visit_time' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time()),
                    'last_login_time' => date('Y-m-d H:i:s', time())
                ]);
            }else{//QQ
                if(!Session::has('openId')){
                    return redirect('company/qqlogin');
                }
                return CompanyUser::create([
                    'username' => $data['username'],
                    'password' => CustomPassword::make($data['password']),
                    'mobile' => $data['mobile'],
                    'contacts' => $data['contacts'],
                    'company_name' => $data['company_name'],
                    'email' => $data['email'],
                    'regip' => getIp(),
                    'phone' => $phone,
                    'qqopenid' => session('openId'),
                    'qqunionid' => session('unionId')?session('unionId'):null,
                    'last_login_ip' => getIp(),
                    'surpris_visit_time' => date('Y-m-d H:i:s', time()),
                    'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                    'regtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time()),
                    'last_login_time' => date('Y-m-d H:i:s', time())
                ]);
            }
        }else{
            return CompanyUser::create([
                'username' => $data['username'],
                'password' => CustomPassword::make($data['password']),
                'mobile' => $data['mobile'],
                'contacts' => $data['contacts'],
                'company_name' => $data['company_name'],
                'email' => $data['email'],
                'regip' => getIp(),
                'phone' => $phone,
                'last_login_ip' => getIp(),
                'surpris_visit_time' => date('Y-m-d H:i:s', time()),
                'mobile_id' => !empty($data['mobile']) ? 1 : 0,
                'regtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time()),
                'last_login_time' => date('Y-m-d H:i:s', time())
            ]);
        }
    }


    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request){
        $this->validateLogin($request);
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)){
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
        $credentials = $this->getCredentials($request);
        //用户名登录
        if(Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))){
            $user = auth()->guard('company')->user();
            //登录记录表
            $this->loginRecord($user);
            return $this->handleUserWasAuthenticated($request, $throttles);
            //手机号码登录
        }else if(Auth::guard('company')->attempt(['mobile' => $credentials['username'], 'password' => $credentials['password']], $request->has('remember'))){
            $user = auth()->guard('company')->user();
            //登录记录表
            $this->loginRecord($user);
            return $this->handleUserWasAuthenticated($request, $throttles);
        }else{
            //试错记录表
            $trial = array();
            $trial['username'] = $request->username;
            $trial['password'] = $request->password;
            $trial['company_login_ip'] = getIp();
            //登录记录表
            CompanyTrialError::create($trial);
        }
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if($throttles && !$lockedOut){
            $this->incrementLoginAttempts($request);
        }

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($user){
        //登录记录表
        $record = array();
        $record['uid'] = $user->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 2;
        $record['type'] = 1;
        //登录记录表
        CompanyLoginRecord::create($record);
        //更新用户表
        $currtime = date('Y-m-d H:i:s', time());
        $fifedate = date('Y-m-d H:i:s', strtotime($user->surpris_visit_time . "+15 day"));
        if($fifedate < $currtime){
            $user->surpris_visit_time = date('Y-m-d H:i:s', time());
            //15天内插入突访记录表
            CompanyVisitRecord::create($record);
        }
        //设置突访时间
        if(empty($user->surpris_visit_time)){
            $user->surpris_visit_time = date('Y-m-d H:i:s', time());
        }
        $user->last_login_time = date('Y-m-d H:i:s', time());
        $user->last_login_ip = getIp();
        $user->save();
    }

    /**
     * 前台登录验证方法
     * @param Request $request
     */
    protected function validateLogin(Request $request){
        $message = [
            $this->loginUsername() . '.required' => '用户名必须填写',
            $this->loginUsername() . '.alpha_dash' => '用户仅允许字母、数字、底线_',
            $this->loginUsername() . '.max' => '用户名称最多32个字符',
            'password.required' => '密码必须填写'
        ];
        $this->validate($request, [
            $this->loginUsername() => 'required|alpha_dash|max:32',
            'password' => 'required',
        ], $message);
    }

    /**
     * 退出
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(){
        session()->forget('company_api');
        Auth::guard('company')->logout();
        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }
}
